package server

import (
	"context"
	"errors"
	"fmt"
	"time"
	user "week41/common/proto"
	"week41/service/inits"
	"week41/service/respotion"
)

func Login(in *user.LoginReq) (*user.LoginResp, error) {
	login, err := respotion.Login(in.Name, in.Password)
	if err != nil {
		return nil, errors.New("登录失败")
	}
	return &user.LoginResp{LoginUserId: int64(login.Id)}, nil
}

func Register(in *user.RegisterReq) (*user.RegisterResp, error) {
	register, err := respotion.Register(in.Name, in.Password)
	if err != nil {
		return nil, errors.New("注册失败")
	}
	return &user.RegisterResp{RegisterUserId: int64(register.Id)}, nil
}

func List(in *user.ListReq) (*user.ListResp, error) {
	result, err := respotion.List()
	if err != nil {
		return nil, errors.New("展示失败")
	}
	var lists []*user.UserList
	for _, users := range result {
		list := user.UserList{
			Id:   int64(users.Id),
			Name: users.Name,
		}
		lists = append(lists, &list)
		inits.RDB.Set(context.Background(), fmt.Sprintf("userlist:%s", lists), lists, time.Hour*24)
	}

	return &user.ListResp{
		List: lists,
	}, nil
}
